package sg.edu.nus.iss.team2s.jass.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import sg.edu.nus.iss.team2s.jass.dto.JobAdvertResponse;

/**
 * IO data access implementation for JobAdvertResponse
 * @author Zheng Xiaofeng
 * @version 1.0
 */

public class JobAdvertResponseDataAccessImpl implements DataAccessI {

	@Override
	public List<Object> parseObjectsFromReader(BufferedReader in) throws IOException {
		List<Object> objList = new ArrayList<Object>();
		String lineStr;
		int lineCount = 0;
		JobAdvertResponse objJobAdvertResponse = null;
		String[] str = new String[7];
		while((lineStr = in.readLine()) != null){
			str[lineCount] = lineStr.substring(lineStr.indexOf("=")+1,lineStr.length());
			lineCount++;
			if(lineCount == str.length){
				objJobAdvertResponse = new JobAdvertResponse(str[0],str[1],str[2],str[3],str[4],str[5],str[6]);
				objList.add(objJobAdvertResponse);
				lineCount = 0;
			}
		}
		return objList;
	}

	@Override
	public void writeObjectsToWriter(List<Object> objects,
			BufferedWriter out) throws IOException {
		int lineCount = 0;
		Iterator<Object> iterator = objects.iterator();
		while(iterator.hasNext()){
			JobAdvertResponse objJobAdvertResponse = (JobAdvertResponse)iterator.next();
			if(objJobAdvertResponse.getJobAdvertResponseId() != null){
			out.write(recordStr("jobAdvertResponseId",lineCount,objJobAdvertResponse.getJobAdvertResponseId()));
			}
			else{
				out.write(recordStr("jobAdvertResponseId",lineCount,String.valueOf(lineCount)));
			}
			out.newLine();
			out.write(recordStr("jobAvertId",lineCount,objJobAdvertResponse.getJobAdvertId()));
			out.newLine();
			out.write(recordStr("jobSeekerId",lineCount,objJobAdvertResponse.getJobSeekerId()));
			out.newLine();
			out.write(recordStr("phone",lineCount,objJobAdvertResponse.getPhone()));
			out.newLine();
			out.write(recordStr("email",lineCount,objJobAdvertResponse.getEmail()));
			out.newLine();
			out.write(recordStr("CV",lineCount,objJobAdvertResponse.getCv()));
			out.newLine();
			out.write(recordStr("action",lineCount,objJobAdvertResponse.getAction()));
			out.newLine();
			lineCount++;
		}
	}

	private String recordStr(String fieldName,int count,String fieldValue)
	{
		if(fieldValue != null){
			return fieldName+count+"="+fieldValue;
		}
		else{
			return fieldName+count+"=";
		}
	}
}
